import { createApp } from 'vue'
import AllComponent from './index'
import NoteTip from '../dialog/NTip.vue'
import { TipProps } from '../dialog/constant'

export default {
  install(app, options) {
    Object.keys(AllComponent).map((component) => {
      if (AllComponent[component].name) {
        app.component(AllComponent[component].name, AllComponent[component])
      }
    })

    // 注册全局使用属性
    app.config.globalProperties.tip = this.tip.bind(this)
    // 提供全局 provide, 局部组件可通过 inject('tip') 获取到全局弹窗函数
    app.provide('tip', app.config.globalProperties.tip)

  },

  // 挂载tip弹窗
  tip(options: TipProps | null) {
    // 创建挂载元素
    if (options?.to && !document.querySelector(options.to)) {
      throw {
        message: `未查找到${options.to}选择器`
      }
    }
    const dom = this.createTipDom()
    const app = createApp(NoteTip, {
      // 卸载函数
      close: () => {
        app.unmount()
        dom?.parentNode?.removeChild(dom)
      },
      ...options
    })
    // 挂在到指定的dom元素上
    app.mount(dom)
  },

  createTipDom() {
    let dom = document.createElement('div')
    dom.className = 'app-note-tip'
    dom.style.width = '100vw'
    dom.style.position = 'absolute'
    document.body.appendChild(dom)
    return dom
  }
}